package com.aifund.app.config.mq;
import com.aifund.app.enums.MqExchangeEnum;
import com.aifund.app.enums.MqQueueEnum;
import com.aifund.app.enums.MqRoutingKeyEnum;
import com.aifund.app.service.impl.mq.MqMessageCallBack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ErrorHandler;


/**
 * @Author : JCccc
 * @CreateTime : 2019/9/3
 * @Description :
 **/
@Configuration
public class DirectRabbitConfig {

    Logger logger = LoggerFactory.getLogger(DirectRabbitConfig.class);
    @Autowired
    MqMessageCallBack mqMessageCallBack;

    //队列 增加新用户队列
    @Bean
    public Queue newApiDirectQueue() {
        // durable:是否持久化,默认是false,持久化队列：会被存储在磁盘上，当消息代理重启时仍然存在，暂存队列：当前连接有效
        // exclusive:默认也是false，只能被当前创建的连接使用，而且当连接关闭后队列即被删除。此参考优先级高于durable
        // autoDelete:是否自动删除，当没有生产者或者消费者使用此队列，该队列会自动删除。
        //   return new Queue("TestDirectQueue",true,true,false);

        //一般设置一下队列的持久化就好,其余两个就是默认false
        return new Queue(MqQueueEnum.NewApiDirectQueue.getQueneName(),true);
    }

    //Direct交换机 起名：TestDirectExchange
    @Bean
    DirectExchange newApiExchange() {
        //  return new DirectExchange("TestDirectExchange",true,true);
        return new DirectExchange(MqExchangeEnum.NewApiDirectExchange.getExchangeName(),true,false);
    }

    //绑定  将队列和交换机绑定, 并设置用于匹配键：NewUserRegister
    @Bean
    Binding bindingDirect() {
        return BindingBuilder.bind(newApiDirectQueue()).to(newApiExchange()).with(MqRoutingKeyEnum.NewApiRegister.getRoutingKey());
    }


    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        //消息没有被队列接收时强行退回而不是丢弃
        template.setMandatory(true);
        /**
         * 消息发送到交换机回调
         */
        template.setConfirmCallback(mqMessageCallBack);
        /**
         * 路由不到队列回调
         */
        template.setReturnsCallback(mqMessageCallBack);

        return template;
    }




    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses("192.168.0.5:5672");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //消息发送到交换机上回调机制
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        //没有发送到指定队列时返回，而不是丢弃消息
        connectionFactory.setPublisherReturns(true);
        return connectionFactory;
    }


    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setErrorHandler(new ErrorHandler() {
            @Override
            public void handleError(Throwable throwable) {
                logger.error("消息消费错误。{}"+throwable.getMessage());
            }
        });
//        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }


}